<template>
  <div class="login-container">
    <!-- <van-nav-bar
      style="background-color: #fff;"
      title="个人中心"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    /> -->
    <div class="main-box">
      <div class="tab-select">
        <div class="tab-item" style="margin-left: 0;" :class="isTab == 'personInfo' ? 'click-tab' : ''" @click="changeTab('personInfo')">
          个人信息
        </div>
        <div class="tab-item" :class="isTab == 'changePassword' ? 'click-tab' : ''" @click="changeTab('changePassword')">
          修改密码
        </div>
        <div class="tab-item" style="margin-right: 0;" :class="isTab == 'cancelAccount' ? 'click-tab' : ''" @click="changeTab('cancelAccount')">
          注销账号
        </div>
        <div class="tab-item" style="margin-right: 0;" :class="isTab == 'cancelLogin' ? 'click-tab' : ''" @click="changeTab('cancelLogin')">
          注销登录
        </div>
      </div>
      <div class="info-box" v-show="isTab == 'personInfo'">
        <van-form ref="infoForm" validate-first @failed="onFailed" @submit="onSubmit">
          <van-cell-group>
            <van-field
              v-model="userName"
              disabled
              readonly
              label="姓名："
              placeholder="请输入姓名"
            />
            <van-field
              v-model="idCardHide"
              disabled
              readonly
              label="身份证号："
              placeholder="请输入身份证号"
            />
            <van-field
              v-model="fieldValue"
              clearable
              required
              is-link
              label="区域："
              placeholder="请选择区域"
              @click="show = true"
              :rules="[{ required: true, message: '请选择区域' }]"
            />
            <van-field
              v-model="phone"
              clearable
              required
              type="tel"
              label="手机号："
              placeholder="请输入手机号"
              maxlength="11"
              :rules="[{ validator: validatorPhone, message: '请填写正确的手机号' }]"
            />
            <van-field
              v-model="bankAccount"
              clearable
              required
              label="银行卡号："
              placeholder="请输入银行卡号"
              :rules="[{ validator: validatorBankAccount, message: '请填写正确的银行卡号' }]"
            />
          </van-cell-group>
          <div class="btn-box">
            <van-button style="width: 99%;" size="small" type="info" native-type="submit">保 存</van-button>
          </div>
        </van-form>
        <div class="btn-box">
          <van-button style="width: 99%;" size="small" type="danger" @click="$router.go(-1)">取 消</van-button>
        </div>
      </div>
      <div class="password-box" v-show="isTab == 'changePassword'">
        <van-form @failed="onFailedPassword" @submit="onSubmitPassword">
          <van-cell-group>
            <van-field
              v-model="oldPassword"
              type="password"
              clearable
              required
              label="原密码"
              placeholder="请输入原密码"
              :rules="[{ validator: validatorPassword, message: '密码采用8位以上且大小写字符数字和特殊字符搭配的方式' }]"
            />
            <van-field
              v-model="password"
              type="password"
              clearable
              required
              label="新密码"
              placeholder="请输入新密码"
              :rules="[{ validator: validatorPassword, message: '密码采用8位以上且大小写字符数字和特殊字符搭配的方式' }]"
            />
            <van-field
              v-model="newPassword"
              type="password"
              clearable
              required
              label="确认密码："
              placeholder="请再次输入新密码"
              :rules="[{ validator: ValidatorPasswordSure, message: '密码需与前一次输入相同' }]"
            />
          </van-cell-group>
          <div class="btn-box">
            <van-button style="width: 99%;" size="small" type="info" native-type="submit">保 存</van-button>
          </div>
        </van-form>
        <div class="btn-box">
          <van-button style="width: 99%;" size="small" type="danger" @click="$router.go(-1)">取 消</van-button>
        </div>
      </div>
      <div class="cancel-account-box" v-show="isTab == 'cancelAccount'">
        <div class="btn-box">
          <van-button style="width: 99%;" size="small" type="danger" @click="dialogShow= true">注销账号</van-button>
        </div>
      </div>
      <div class="cancel-account-box" v-show="isTab == 'cancelLogin'">
        <div class="btn-box">
          <van-button style="width: 99%;" size="small" type="danger" @click="showLogoutDialog= true">注销登录</van-button>
        </div>
      </div>
      <van-popup v-model="show" round position="bottom">
        <van-cascader
          v-model="cascaderValue"
          title="请选择所在地区"
          :options="options"
          @finish="onFinish"
        />
      </van-popup>
      <van-dialog v-model="dialogShow" title="输入密码确认(注:将清除账号信息)" @confirm="setDialog" show-cancel-button>
        <van-field
          v-model="cancelPassword"
          type="password"
          clearable
          center
          label-align="right"
          input-align="left"
          label="确认密码"
          placeholder="请输入密码确认注销"
        />
      </van-dialog>
      <van-dialog v-model="showLogoutDialog" title="请确认是否退出登录？" @confirm="setLogoutDialog" show-cancel-button>
      </van-dialog>
    </div>
  </div>
</template>

<script>
import Crypto from '@/utils/crypto.js'
import { getAreaInfo } from '@/api/common'
import { changePersonInfo, resetPassword, getPersonInfo, cancellationUser } from '@/api/personcenter'
export default {
  name: 'login',
  data () {
    return {
      showLogoutDialog: false, // 显示退出登录对话框
      dialogShow: false, // 显示对话框
      isTab: 'personInfo', // 切换tab
      cascaderValue: '',
      options: [
        {
          text: '邯郸市',
          value: '130400',
          children: []
        }
      ],
      show: false, // 显示对话框
      bankAccount: '', // 银行卡号
      bankAccountShow: '',
      bankAccountHide: '',
      areaId: '', // 区域id
      fieldValue: '', // 显示在输入框的地区名称
      idCard: '', // 身份证号
      idCardHide: '',
      password: '', // 密码
      phone: '', // 手机号
      userName: '', // 用户名
      oldPassword: '', // 旧密码
      newPassword: '', // 新密码
      cancelPassword: '' // 注销登录的密码
    }
  },
  created () {
    this.getPersonInfo('first')
    this.getAreaId()
  },
  methods: {
    // 失去焦点时
    blurBank () {
      this.bankAccountShow = this.bankAccount
    },
    // 聚焦时显示
    focusBank () {
      this.bankAccount = this.bankAccountShow
    },
    // 展示退出登录对话框
    setLogoutDialog () {
      this.showLogoutDialog = false
      this.$store.dispatch('LogOut').then(res => {
        this.$router.push('/login')
        this.$toast(res)
      })
    },
    // 控制对话框
    setDialog () {
      if (this.cancelPassword === '') {
        this.$toast('请先输入密码')
        return
      }
      this.dialogShow = false
      this.cancelAccount()
    },
    // 全部选项选择完毕后，会触发 finish 事件
    onFinish ({ selectedOptions }) {
      this.show = false
      this.areaId = this.cascaderValue
      this.fieldValue = selectedOptions.map((option) => option.text).join('/')
    },
    // 成功校验个人信息
    onSubmit () {
      this.changeUserInfo()
    },
    // 失败校验个人信息
    onFailed () {
      this.$toast('请先将个人信息填写正确！')
    },
    // 成功校验密码
    onSubmitPassword () {
      this.resetPassword()
    },
    // 失败校验密码
    onFailedPassword () {
      this.$toast('请先将密码信息填写正确！')
    },
    // 获取区域列表
    getAreaId () {
      getAreaInfo({
        parentId: 130400
      }).then(res => {
        res.data.forEach(value => {
          if (value.id === this.areaId) {
            this.fieldValue = '邯郸市/' + value.label
          }
          this.options[0].children.push({
            text: value.label,
            value: value.id
          })
        })
      })
    },
    // 修改用户个人信息
    changeUserInfo () {
      changePersonInfo({
        areaId: this.areaId,
        bankAccount: Crypto.encrypt(this.bankAccount, this.aesKey, this.aesKeyIv),
        idCard: Crypto.encrypt(this.idCard, this.aesKey, this.aesKeyIv),
        phone: this.phone,
        userName: this.userName,
        userId: localStorage.getItem('userId')
      }).then(res => {
        if (res.msg === '修改成功') {
          this.getPersonInfo()
          // this.bankAccount = this.bankAccount.replace(/(\w{6})\w*(\w{4})/, '$1********$2')
          this.$toast('个人信息修改成功！')
        }
      })
    },
    // 重置个人密码
    resetPassword () {
      const mydata = {
        userId: parseInt(localStorage.getItem('userId')),
        oldPassword: Crypto.encrypt(this.oldPassword, this.aesKey, this.aesKeyIv),
        newPassword: Crypto.encrypt(this.newPassword, this.aesKey, this.aesKeyIv)
      }
      const formdata = new FormData()
      formdata.append('link', JSON.stringify(mydata))
      for (const key in mydata) {
        formdata.append(key, mydata[key])
      }
      resetPassword(formdata).then(res => {
        if (res.msg === '修改密码失败，旧密码错误') {
          this.$toast('修改失败，旧密码错误')
        } else if (res.msg === '修改成功') {
          this.$toast('密码修改成功')
          this.password = ''
          this.oldPassword = ''
          this.newPassword = ''
        } else if (res.msg === '新密码不能与旧密码相同') {
          this.$toast('新密码不能与旧密码相同')
        }
      })
    },
    // 注销账号
    cancelAccount () {
      const mydata = {
        userId: parseInt(localStorage.getItem('userId')),
        password: Crypto.encrypt(this.cancelPassword, this.aesKey, this.aesKeyIv)
      }
      const formdata = new FormData()
      formdata.append('link', JSON.stringify(mydata))
      for (const key in mydata) {
        formdata.append(key, mydata[key])
      }
      cancellationUser(formdata).then(res => {
        if (res.code === 200) {
          this.$toast(res.msg)
          this.$store.dispatch('LogOut') // 注销后清除本地的登录数据
          this.$router.push('/login')
        } else if (res.code === 500) {
          this.$toast(res.msg)
        }
      })
    },
    // 获取用户信息
    getPersonInfo (flag) {
      getPersonInfo(localStorage.getItem('userId')).then(res => {
        if (res.code !== 200) {
          this.$toast('个人信息获取失败，请重新进入页面！')
          return
        }
        this.areaId = res.data.areaId
        this.bankAccount = Crypto.decrypt64(res.data.bankAccount, this.aesKey, this.aesKeyIv)
        this.idCard = Crypto.decrypt64(res.data.idCard, this.aesKey, this.aesKeyIv)
        this.idCardHide = this.idCard.replace(/(\w{6})\w*(\w{4})/, '$1********$2')
        this.phone = res.data.phone
        this.userName = res.data.userName
        if (flag === 'first') {
          this.bankAccount = this.bankAccount.replace(/(\w{6})\w*(\w{4})/, '$1********$2')
        }
      })
    },
    // 切换tab
    changeTab (tabname) {
      this.isTab = tabname
    },
    // 校验函数返回 true 表示校验通过，false 表示不通过
    validatorIdCard (val) {
      return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(val)
    },
    // 校验手机号
    validatorPhone (val) {
      return /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(val)
    },
    // 校验银行卡号
    validatorBankAccount (val) {
      return /^([1-9]{1})(\d{14}|\d{15}|\d{16}|\d{18})$/.test(val)
    },
    // 校验密码
    validatorPassword (val) {
      return /^(?![A-z0-9]+$)(?=.[^%&',;=?$\x22])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,20}$/.test(val)
    },
    // 前后密码校验
    ValidatorPasswordSure () {
      return this.password === this.newPassword
    }
  }
}
</script>

<style scoped lang="less">
.login-container{
  min-height: 100vh;
  background-color: #f8f8f8;
  .main-box{
    height: 470px;
    width: 94%;
    margin: 0 3% 10px 3%;
    padding-top: 10px;
    font-size: 14px;
    .tab-select{
      display: flex;
      height: 35px;
      .tab-item{
        flex: 22%;
        margin: 0 8px;
        line-height: 35px;
        text-align: center;
        border-radius: 17px;
        color: #9b9b9b;
        background-color: #fff;
      }
      .click-tab{
        color: #fff;
        background-color: #1989fa;
      }
    }
    .person-info{
      font-size: 14px;
      padding-left: 10px;
      color: #5f93ed;
    }
    .info-box{
      height: 219px;
      margin-top: 15px;
      padding: 5px;
      border-radius: 5px;
      background-color: #fff;
    }
    .cancel-account-box{
      height: 120px;
      .btn-box{
        margin-top: 80px;
      }
    }
    .password-set{
      margin: 10px 0;
      font-size: 14px;
      padding-left: 10px;
      color: #5f93ed;
    }
    .password-box{
      margin: 10px 0;
      height: 135px;
      border-radius: 5px;
      padding: 5px;
      background-color: #fff;
    }
    .btn-box{
      margin-top: 20px;
      text-align: center;
      .login-box{
        margin-top: 50px;
        font-size: 14px;
        color: #5f93ed;
      }
      .register{
        display: inline-block;
        padding-left: 15px;
        cursor: pointer;
      }
    }
  }
}
</style>
